<?php
/**
 * 站点配置管理
 *
 */
class siteconf
{
	private $site_conf;
	private $conf_file;
	
	public function __construct($conf_file)
	{
		$this->conf_file = $conf_file;
		$this->site_conf = array();
		$this->_get_site_conf();
	}
	
	/**
	 * 获取站点配置
	 *
	 * @return array
	 */
	private function _get_site_conf()
	{
		if(!file_exists($this->conf_file))
		{
			$this->site_conf = array();
			return false;
		}
		$res = array();
		$tmp = file($this->conf_file);
		if(is_array($tmp))
		{
			foreach ($tmp as $t)
			{
				$tmp = trim($t);
				$arr = explode('=', $tmp);
				if(sizeof($arr) == 2)
				{
					list($tkey, $tvalue) = explode('=', $tmp);
					$res[trim($tkey)] = $this->_conf_decode(trim($tvalue));
				}
			}
		}
		$this->site_conf = $res;
		return true;
	}
	
	public function get_site_conf()
	{
		return $this->site_conf;
	}

    /**
     * 根据索引获取配置项的值
     * @author menghao
     * @param <string> $key
     * @return <mixed>
     */
    public function get($key)
    {
        return @get_null($this->site_conf[$key]);
    }

    /**
     * 设置站点配置项
     *
     * @param string $key
     * @param string $value
     * @return bool
     */
	public function set_site_conf($key, $value)
	{
		$this->site_conf[$key] = $value;
		$this->_save_conf();
		return true;
	}
	
	/**
	 * 删除站点配置项
	 *
	 * @param string $key
	 * @return bool
	 */
	public function del_site_conf($key)
	{
		if(array_key_exists($key, $this->site_conf))
		{
			unset($this->site_conf[$key]);
		}
		$this->_save_conf();
		return true;
	}
	
	private function _save_conf()
	{
		$str = '';
		if(is_array($this->site_conf))
		{
			foreach ($this->site_conf as $k=>$v)
			{
				$str .= $k . "	=	" . $this->_conf_encode($v) . "\n";
			}
		}
		$fp = fopen($this->conf_file, 'w');
		fwrite($fp, $str);
		fclose($fp);
	}
	
	private function _conf_encode($conf)
	{
		$temp = str_replace('=', '__edufe_equal__', base64_encode($conf));
		$str = '';
		$start = 0;
		for($i=1;1==1;$i++)
		{
			$tmp = substr($conf,$start,3) . substr(CONF_KEY,$i%(strlen(CONF_KEY)+1),1);
			$str .= $tmp;
			$start+=3;
			if(strlen($tmp) != 4)
			{
				break;
			}
		}
		return $temp;
	}
	
	private function _conf_decode($conf)
	{
		$res = '';
		$key = '';
		for ($i=0;$i<strlen($conf);$i++)
		{
			$tmp = substr($conf,$i,1);
			if($i%4 == 4)
			{
				$key .= $tmp;
			}
			else 
			{
				$res .= $tmp;
			}
		}
		$keysize = strlen($key) > strlen(CONF_KEY) ? strlen(CONF_KEY) : strlen($key);
		if(substr($key, 0, $keysize) == substr(CONF_KEY, 0 , $keysize))
		{
			return base64_decode(str_replace('__edufe_equal__','=',$res));
		}
		return false;
	}

}
?>